package ui;

import domain.Player;
import service.AttributeService;
import service.GameService;


import javax.swing.*;
import java.awt.*;

/**
 * 选择属性界面（UI 层，只负责界面展示和事件监听，将业务逻辑委托给服务层去做）
 * 页面美化: bijiajun, szy
 * 负责人: 景旭（UI 部分），业务逻辑已抽取到 AttributeService
 */
public class SelectAttributesJFrame extends JFrame {

    public static Player player;
    private JButton returnMenu;
    private JButton startGame;
    private JTextField[] jTextFields = new JTextField[5];
    private JTextField textFieldName;

    // 彩蛋标记：是否触发了“坏运气”惩罚
    private boolean flagBadLuck = false;
    public SelectAttributesJFrame() {
        player = new Player();
        // 1. 先触发彩蛋逻辑
        flagBadLuck = AttributeService.triggerEgg(player);
        // 2. 初始化界面
        initJFrame();
        initView();
        initJMenuBar();
        initImage();
        // 3. 让界面可见必须放在最后
        this.setVisible(true);
    }
    /**
     * 初始化所有标签、文本框、加减按钮等
     */
    private void initView() {
        String[] attributes = {"智力", "体质", "颜值", "家境", "运气"};
        int y = 80;
        for (int i = 0; i < attributes.length; i++) {
            int index = i;

            JLabel label = new JLabel(attributes[i] + " :");
            label.setBounds(240, y, 50, 30);
            label.setFont(new Font("微软雅黑", Font.BOLD, 13));
            this.add(label);

            JTextField attrField = new JTextField("0");
            attrField.setBounds(290, y, 40, 30);
            this.add(attrField);
            jTextFields[i] = attrField;

            JButton minusBtn = new JButton("-");
            minusBtn.setBounds(170, y, 50, 30);
            minusBtn.setBackground(new Color(114, 169, 244));
            this.add(minusBtn);
            minusBtn.addActionListener(e -> {
                Utils.Music.playSound("src\\music\\02.wav");
                int currentVal = Integer.parseInt(jTextFields[index].getText());
                if (currentVal > 0) {
                    attrField.setText(String.valueOf(currentVal - 1));
                } else {
                    JOptionPane.showMessageDialog(this, "属性不能为负数!");
                }
            });


            JButton plusBtn = new JButton("+");
            plusBtn.setBounds(340, y, 50, 30);
            plusBtn.setBackground(new Color(61, 139, 246));
            this.add(plusBtn);
            plusBtn.addActionListener(e -> {
                Utils.Music.playSound("src\\music\\02.wav");
                int sum = 0;
                for (JTextField jtf : jTextFields) {
                    sum += Integer.parseInt(jtf.getText());
                }
                if (sum < 25) {
                    int currentVal = Integer.parseInt(attrField.getText());
                    attrField.setText(String.valueOf(currentVal + 1));
                } else {
                    JOptionPane.showMessageDialog(this, "属性和不能大于25!");
                }
            });

            y += 62;
        }

        // 玩家昵称输入
        JLabel labelName = new JLabel("输入这一世你的昵称:");
        labelName.setFont(new Font("楷体", Font.BOLD, 18));
        labelName.setBounds(120, 400, 180, 30);
        this.add(labelName);

        textFieldName = new JTextField();
        textFieldName.setBounds(300, 400, 150, 30);
        this.add(textFieldName);

        // “重启人生”按钮
        startGame = new JButton("重启人生!");
        startGame.setBounds(100, 500, 120, 60);
        startGame.setBackground(new Color(253, 222, 122));
        this.add(startGame);

        // “返回主菜单”按钮
        returnMenu = new JButton("返回主菜单");
        returnMenu.setBounds(350, 500, 120, 60);
        returnMenu.setBackground(new Color(253, 222, 122));
        this.add(returnMenu);
        bindActions();
    }
    private void bindActions() {
        // 点击“重启人生!”按钮
        startGame.addActionListener(e -> {
            Utils.Music.playSound("src\\music\\02.wav");
            int[] inputs = new int[5];
            int sum = 0;

            try {
                for (int i = 0; i < 5; i++) {
                    inputs[i] = Integer.parseInt(jTextFields[i].getText());
                    sum += inputs[i];
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的数字！");
                return;
            }

            if (sum > 25) {
                JOptionPane.showMessageDialog(this, "属性不能大于25");
                return;
            }

            String name = textFieldName.getText();
            player.setName(name);
            AttributeService.applyAttributes(player, inputs, flagBadLuck);

            new GameJFrame();
            this.dispose();
            GameService.deathAge(player);
        });

        returnMenu.addActionListener(e -> {
            Utils.Music.playSound("src\\music\\02.wav");
            new GameMenuJFrame();
            this.setVisible(false);
        });
    }
    private void initJFrame() {
        this.setSize(603, 680);
        this.setTitle("人生重开模拟器 v1.0");
        this.setAlwaysOnTop(true);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(null);
    }

    private void initJMenuBar() {
        JLabel title = new JLabel("分配属性");
        title.setFont(new Font("微软雅黑", Font.BOLD, 22));
        title.setBounds(this.getWidth() / 2 - 50, 0, 100, 80);
        this.add(title);
    }

    private void initImage() {
        JLabel background = new JLabel(new ImageIcon(this.getClass().getResource("/image/RegisterJFrame/背景.png")));
        background.setBounds(0, 0, 603, 680);
        this.getContentPane().add(background);
    }
}
